package com.education.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.education.realtime.app.BaseAppV1;
import com.education.realtime.app.BaseSQLApp;
import com.education.realtime.bean.AnswerCountBean;
import com.education.realtime.bean.AnswerRightCountBean;
import com.education.realtime.common.Constant;
import com.education.realtime.util.AtguiguUtil;
import com.education.realtime.util.FlinkSinkUtil;
import com.education.realtime.util.SqlUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class DwsAnswerCount extends BaseAppV1 {
    public static void main(String[] args) {
        new DwsAnswerCount().init(3155, "DwsAnswerCount",Constant.TOPIC_DWD_EXAM_ISSUE);
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        stream
                .map(JSON::parseObject)
                .assignTimestampsAndWatermarks(WatermarkStrategy
                        .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner((obj,ts)->obj.getLong("ts")*1000)
                )
                .keyBy(obj->obj.getString("question_id"))
                .process(new KeyedProcessFunction<String, JSONObject, AnswerCountBean>() {

                    @Override
                    public void processElement(JSONObject obj,
                                               Context ctx,
                                               Collector<AnswerCountBean> collector) throws Exception {
                        long ct=0L;
                        Long ts = obj.getLong("ts");
                        String is_correct = obj.getString("is_correct");
                        if ("1".equals(is_correct)){
                            ct+=1;
                        }
                        String question_id = obj.getString("question_id");
                        AnswerCountBean answerRightCountBean = new AnswerCountBean("","",ct, question_id, ts);
                        collector.collect(answerRightCountBean);
                    }
                })
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<AnswerCountBean>() {
                            @Override
                            public AnswerCountBean reduce(AnswerCountBean b1, AnswerCountBean b2) throws Exception {
                                b1.setCt(b1.getCt()+b2.getCt());
                                return b1;
                            }
                        },
                        new ProcessAllWindowFunction<AnswerCountBean, AnswerCountBean, TimeWindow>(){
                            @Override
                            public void process(Context ctx,
                                                Iterable<AnswerCountBean> elements,
                                                Collector<AnswerCountBean> out) throws Exception {
                                String stt = AtguiguUtil.toDateTime(ctx.window().getStart());
                                String edt = AtguiguUtil.toDateTime(ctx.window().getEnd());
                                AnswerCountBean bean = elements.iterator().next();
                                bean.setStt(stt);
                                bean.setEdt(edt);
                                bean.setTs(System.currentTimeMillis());
                                out.collect(bean);
                            }
                        }
                )
                .addSink(FlinkSinkUtil.getClickHouseSink(Constant.CLICKHOUSE_DB,
                        "dws_exam_answer_window",
                        AnswerCountBean.class));


    }
}

